<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
      </div>

      <el-form ref="productForm" :model="form" :rules="rules" v-loading="loading" label-width="80px" class="store-creat">
        <el-form-item label="货品名称" prop="name" >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="货品简介">
          <el-input v-model="form.info"></el-input>
        </el-form-item>
        <el-form-item label="货品分类">
          <el-select 
            v-model="form.cate_id" 
            placeholder="请选择分类" 
            style="width: 100%">
            <el-option
              v-for="cate in categorys"
              :key="cate.id"
              :label="cate.name"
              :value="cate.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货品价格" prop="price">
          <div class="pirce-group">
            <div class="pirce-group-num">
              <el-input v-model="form.price" type="number" @blur="priceFormat" ></el-input>
            </div>
            <div class="pirce-group-mid">
              <span>元 /</span>
            </div>
            <div class="pirce-group-unit" >
              <el-input v-model="form.unit" placeholder="单位" ></el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="货品规格">
          <el-input v-model="form.spec"></el-input>
        </el-form-item>
        <el-form-item label="发货地址">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="物流方式">
          <el-select v-model="form.logistics_mode" multiple style="width: 100%" placeholder="请选择">
            <el-option
              v-for="item in logistics"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货品描述">
          <el-input type="textarea" v-model="form.desc"></el-input>
        </el-form-item>
        <el-form-item label="货品封面">
          <el-upload
            class="Cover-uploader"
            action=""
            :http-request="coverUpload"
            name="cover-img"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload">
            <img v-if="form.cover_image.url" :src="form.cover_image.url" class="Cover">
            <i v-else class="el-icon-plus Cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="货品组图">
          <el-upload
            class="upload-demo"
            name="cover-img"
            action="http://www.cray.com/api/admin/products/uploadpic"
            :headers="headers"
            :on-preview="handlePreview"
            :on-success="handlePicSuccess"
            :on-remove="handleRemove"
            :file-list="form.pic_group"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ submitText }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { show, create, update, coverUpload } from '@/api/product'
import { fetchList as getCateList } from '@/api/category'

export default {
  name: 'order-creat',
  data() {
    return {
      title: this.$route.params.id ? '更新货品' : '添加货品',
      isEdit: this.$route.params.id,
      form: {
        name: '',
        info: '',
        desc: '',
        spec: '',
        price: '',
        unit: '公斤',
        address: '',
        logistics_mode: [],
        cover_image: { name: '', url: '', value: '' },
        pic_group: [],
        cate_id: 0
      },
      logistics: ['协助找车', '支持走快递', '支持走空运', '支持周边送货', '支持零担拼车'],
      pics: [],
      // 上传图片需要的头部信息
      headers: { 'Authorization': 'Bearer ' + getToken() },
      rules: {
        name: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入货品价格', trigger: 'blur' }]
      },
      submitText: this.$route.params.id ? '保存更新' : '立即创建',
      categorys: null,
      loading: false
    }
  },
  created() {
    if (this.isEdit) {
      this.loading = true
      const id = this.$route.params.id // 货品ID
      show(id).then(res => {
        if (res.status === 'success') {
          this.form.name = res.data.name
          this.form.price = res.data.price
          this.form.unit = res.data.unit
          this.form.info = res.data.info
          this.form.spec = res.data.spec
          this.form.address = res.data.address
          this.form.logistics_mode = res.data.logistics_mode
          this.form.desc = res.data.description
          this.form.cate_id = res.data.cate_id
          this.form.cover_image = {
            name: '封面图片',
            url: res.data.cover_image_url,
            value: res.data.cover_image
          }
          res.data.pic_group.forEach((ele, index) => {
            this.form.pic_group.push({ name: '图-' + (index + 1), url: res.data.image_base_url + ele, value: ele })
          })
          this.loading = false
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
    this.getCateList()
  },
  methods: {
    onSubmit() {
      this.$refs['productForm'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateProduct(this.form, this.isEdit)
          } else {
            this.createProduct(this.form)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取分类
    getCateList() {
      getCateList({}).then(res => {
        this.categorys = res.data
      }).catch(err => {
        console.log(err)
      })
    },
    // 创建商品
    createProduct(data) {
      create(data).then(res => {
        if (res.status === 'success') {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.$store.dispatch('delVisitedViews', { name: 'store' }) // 清除keep-alive
          setTimeout(() => {
            this.$router.push({ name: 'store' })
          }, 1000)
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 更新商品
    updateProduct(data, id) {
      update(data, id).then(res => {
        if (res.status === 'success') {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.$store.dispatch('delVisitedViews', { name: 'store' }) // 清除keep-alive
          setTimeout(() => {
            this.$router.push({ name: 'products' })
          }, 1000)
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleCoverSuccess(res, file) {
      this.form.cover_image = URL.createObjectURL(file.raw)
    },
    beforeCoverUpload(file) {
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.name)) {
        this.$message.error('上传图片只能是、jpg、png、jpeg格式!')
        return false
      }
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
    },
    priceFormat() {
      if (this.form.price) {
        this.form.price = parseFloat(this.form.price).toFixed(2)
      }
    },
    handleRemove(file, fileList) {
      for (var index in this.form.pic_group) {
        if (file.uid === this.form.pic_group[index].uid) {
          this.form.pic_group.splice(index, 1)
          break
        }
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    // 封面图片上传
    coverUpload(param) {
      var form = new FormData()
      form.append(param.filename, param.file)
      coverUpload(form).then(res => {
        // param.onSuccess()
        this.form.cover_image.name = '封面图片'
        this.form.cover_image.url = res.data.path
        this.form.cover_image.value = res.data.name
      }).catch(err => {
        console.log(err)
      })
    },
    // 组图上传
    picsUpload(param) {
      var form = new FormData()
      form.append(param.filename, param.file)
      coverUpload(form).then(res => {
        this.form.cover_image = res.data.path
        // param.onSuccess()
        this.$message.success('上传成功')
      }).catch(err => {
        console.log(err)
      })
    },
    // 组图上传成功回调
    handlePicSuccess(res, file, fileList) {
      if (res.status === 'success') {
        this.form.pic_group.push({ name: res.data.name, url: res.data.path, uid: file.uid, value: res.data.name })
      }
    }
  },
  computed: {
  }
}
</script>

<style lang="scss">
  .store-creat {
    width: 60%;
  }

  .store-creat .line {
      text-align: center;
  }

  .store-creat .el-checkbox-group .el-checkbox {
    float: left;
    width: 160px;
    padding-right: 20px;
    margin: 0;
    padding: 0;
}

.app-main .tip {
    padding: 8px 16px;
    background-color: #ecf8ff;
    border-radius: 4px;
    // border-left: 5px solid #50bfff;
    margin: 20px 0;
    margin-top: 10px;
    p {
    font-size: 14px;
    color: #5e6d82;
    line-height: 1.5em;
  }
}

.pirce-group {
  .pirce-group-num {
    width: 220px;
    float: left;
  }
  .pirce-group-mid {
    float: left;
    padding: 0 10px;
  }
  .pirce-group-unit {
    width: 100px;
    float: left;
  }
}
.Cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.Cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.Cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.Cover {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

